<!-- Horizontal Form -->
<div class="box box-info">
    <div class="box-header with-border">
        <h3 class="box-title">添加供应商</h3>
        <h3 class="msg"></h3>
    </div>
    <!-- /.box-header -->
    <!-- form start -->
    <form class="form-horizontal">
        <div class="box-body">
            <input hidden type="text" name="id" id="spuId">
            <div class="form-group">
                <label for="goodsSnId" class="col-sm-2 control-label">编号</label>
                <div class="col-sm-10">
                    <input type="text" name="goodsSn" class="form-control" id="goodsSnId">
                </div>
            </div>
            <div class="form-group">
                <label for="nameId" class="col-sm-2 control-label">名称</label>

                <div class="col-sm-10">
                    <input type="text" name="name" class="form-control" id="nameId">
                </div>
            </div>


            <div class="form-group">
                <label for="categoryId" class="col-sm-2 control-label">商品分类</label>
                <select style="margin-left: 12px;display: inline-block ;height: 30px;width: 200px; "
                        th:with="type=${@categoryServiceImpl.selectCategoryList1()}" id="categoryId" name="categoryId">
                    <option th:each="shop : ${type}" th:text="${shop.name}" th:value="${shop.id}"></option>
                </select>
            </div>
            <div class="form-group">
                <label for="shopId" class="col-sm-2 control-label">归属店铺</label>
                <select style="margin-left: 12px;display: inline-block ;height: 30px;width: 200px; "
                        th:with="type=${@shopServiceImpl.selectShopList1()}" id="shopId" name="shopId">
                    <option th:each="shop : ${type}" th:text="${shop.name}" th:value="${shop.id}"></option>
                </select>
            </div>
            <div class="form-group">
                <label for="brandId" class="col-sm-2 control-label">所属供应商</label>
                <select style="margin-left: 12px;display: inline-block ;height: 30px;width: 200px; "
                        th:with="type=${@brandServiceImpl.selectBrandList1()}" id="brandId" name="brandId">
                    <option th:each="shop : ${type}" th:text="${shop.name}" th:value="${shop.id}"></option>
                </select>
            </div>
            <div class="form-group">
                <label for="images" class="col-sm-2 control-label">相册</label>
                <div class="col-sm-10" id="imagesDiv">
                    <input type="text" name="gallery" id="imagesValueId" hidden>
                    <input type="file" multiple id="images"/>
                </div>
            </div>

            <div class="form-group">
                <label for="keywordsId" class="col-sm-2 control-label">商品关键字</label>
                <div class="col-sm-10">
                    <input type="text" name="keywords" class="form-control" placeholder="请使用,号隔开" id="keywordsId">
                </div>
            </div>
            <div class="form-group">
                <label for="numId" class="col-sm-2 control-label">库存</label>
                <div class="col-sm-10">
                    <input type="text" name="num" class="form-control" id="numId">
                </div>
            </div>


            <div class="form-group">
                <label for="briefId" class="col-sm-2 control-label">商品简介</label>
                <div class="col-sm-10">
                    <input type="text" name="brief" class="form-control" id="briefId">
                </div>
            </div>

            <div class="form-group">
                <label for="isOnSaleId" class="col-sm-2 control-label">是否上架</label>
                <div class="col-sm-10">
                    <input value="0" type="checkbox" name="isOnSale" class="form-control" id="isOnSaleId" >
                </div>
            </div>
            <div class="form-group">
                <label for="sortOrderId" class="col-sm-2 control-label">排序号</label>
                <div class="col-sm-10">
                    <input type="text" name="sortOrder" class="form-control" id="sortOrderId">
                </div>
            </div>

            <div class="form-group">
                <label for="ImagesId" class="col-sm-2 control-label">封面</label>
                <div class="col-sm-10">
                    <input hidden type="text" name="picUrl" id="picUrlId">
                    <input type="file" onchange="changeImage()" id="ImagesId" multiple="multiple"
                           accept="image/*"/>更改图片
                    <img id="gimage" style="width: 100px;height: 50px"
                         src="https://img2.baidu.com/it/u=3345545820,3704361652&fm=253&fmt=auto&app=138&f=JPEG?w=260&h=261">
                </div>
            </div>

            <div class="form-group">
                <label for="isNewId" class="col-sm-2 control-label">是否新品</label>
                <div class="col-sm-10">
                    <input value="0" type="checkbox" name="isNew" class="form-control" id="isNewId" >
                </div>
            </div>

            <div class="form-group">
                <label for="isHotId" class="col-sm-2 control-label">是否热卖</label>
                <div class="col-sm-10">
                    <input value="0" type="checkbox" name="isHot" class="form-control" id="isHotId" >
                </div>
            </div>

            <div class="form-group">
                <label for="unitId" class="col-sm-2 control-label">单位</label>
                <div class="col-sm-10">
                    <input type="text" name="unit" class="form-control" id="unitId">
                </div>
            </div>

            <div class="form-group">
                <label for="counterPriceId" class="col-sm-2 control-label">零售价格</label>
                <div class="col-sm-10">
                    <input type="text" name="counterPrice" class="form-control" id="counterPriceId">
                </div>
            </div>
            <div class="form-group">
                <label for="retailPriceId" class="col-sm-2 control-label">批发价格</label>
                <div class="col-sm-10">
                    <input type="text" name="retailPrice" class="form-control" id="retailPriceId">
                </div>
            </div>

            <!--detail  富文本编辑器  百度-->
            <div class="form-group">
                <label for="editor" class="col-sm-2 control-label">商品详情</label>
                <div class="col-sm-10">
                   <textarea name="detail" id="editor"
                             style="width: 820px; height: 200px;"></textarea>
                </div>
            </div>
        </div>
        <!-- /.box-body -->
        <div class="box-footer">
            <button type="button" class="btn btn-default btn-cancel">Cancel</button>
            <button type="button" class="btn btn-info pull-right btn-save">Save</button>
        </div>
        <!-- /.box-footer -->
    </form>
    <div class="layui-layer layui-layer-page layui-layer-molv layer-anim" id="treeLayer" type="page" times="2"
         showtime="0" contype="object"
         style="z-index:59891016; width: 300px; height: 450px; top: 100px; left: 500px; display:none">
        <div class="layui-layer-title" style="cursor: move;">选择部门</div>
        <div class="layui-layer-content" style="height: 358px;">
            <div style="padding: 10px;" class="layui-layer-wrap">
                <ul id="zTreeId" class="ztree"></ul>    <!-- 动态加载树 -->
            </div>
        </div>
        <span class="layui-layer-setwin"> <a
                class="layui-layer-ico layui-layer-close layui-layer-close1 btn-cancel"></a></span>
        <div class="layui-layer-btn layui-layer-btn-">
            <a class="layui-layer-btn0 btn-confirm">确定</a>
            <a class="layui-layer-btn1 btn-cancel">取消</a>
        </div>
    </div>
</div>
<link href="/bootstrap-switch/dist/bootstrap-switch.min.css" type="text/css" rel="stylesheet"/>
<script src="/bootstrap-switch/dist/bootstrap-switch.min.js"></script>
<script type="text/javascript" src="bower_components/ztree/jquery.ztree.all.min.js"></script>
<script type="text/javascript" src="bower_components/layer/layer.js"></script>
<!--富文本需要的内容添加到了starter.html中了-->

<script type="text/javascript">


    $(document).ready(function () {
        $(".box-footer")
            .on("click", ".btn-cancel", doCancel)
            .on("click", ".btn-save", doSaveOrUpdate);

        /*富文本编辑器*/
        var ue = window.UE.getEditor('editor');
        //根据不同action上传图片和附件
        window.UE.Editor.prototype._bkGetActionUrl = window.UE.Editor.prototype.getActionUrl;
        window.UE.Editor.prototype.getActionUrl = function (action) {
            if (action == 'uploadimage') {
                return '/file/uploadFwb'; //图片上传 的路径 需要新建UploadController
            } else if (action == 'uploadfile') {
                return '/upload/uploadfile';//文件上传的路径 需要新建UploadController
            } else {
                return this._bkGetActionUrl.call(this, action);
            }
        }
        //  表单开关控件 是否启用
        //name值和input标签的name值一样
        $("[name='isOnSale']").bootstrapSwitch({
            onText: "上架",      // 设置ON文本
            offText: "下架",    // 设置OFF文本
            onColor: "success",// 设置ON文本颜色(info/success/warning/danger/primary)
            offColor: "warning",  // 设置OFF文本颜色 (info/success/warning/danger/primary)
            size: "mini",    // 设置控件大小,从小到大  (mini/small/normal/large)
            // 当开关状态改变时触发
            onSwitchChange: function (event, state) {
                if (state == true) {
                    // console.log("我是OnSale,我被选中了true 赋值为1")
                    $("#isOnSaleId").val(1)
                } else {
                    // console.log("我是OnSale,我被选中了false 赋值为0")
                    $("#isOnSaleId").val(0)
                }
            }
        });
        /*是否新品*/
        $("[name='isNew']").bootstrapSwitch({
            onText: "新品",      // 设置ON文本
            offText: "默认",    // 设置OFF文本
            onColor: "success",// 设置ON文本颜色(info/success/warning/danger/primary)
            offColor: "warning",  // 设置OFF文本颜色 (info/success/warning/danger/primary)
            size: "mini",    // 设置控件大小,从小到大  (mini/small/normal/large)
            // 当开关状态改变时触发
            onSwitchChange: function (event, state) {
                if (state == true) {
                    // console.log("我是isNew,我被选中了true 赋值为1")
                    $("#isNewId").val(1)
                } else {
                    // console.log("我是isNew,我被选中了false 赋值为0")
                    $("#isNewId").val(0)
                }
            }
        });
        /*是否热卖*/
        $("[name='isHot']").bootstrapSwitch({
            onText: "热卖", // 设置ON文本
            offText: "默认",    // 设置OFF文本
            onColor: "success",// 设置ON文本颜色(info/success/warning/danger/primary)
            offColor: "warning",  // 设置OFF文本颜色 (info/success/warning/danger/primary)
            size: "mini",    // 设置控件大小,从小到大  (mini/small/normal/large)
            // 当开关状态改变时触发
            onSwitchChange: function (event, state) {
                if (state == true) {
                    // console.log("我是isHot,我被选中了true 赋值为1")
                    $("#isHotId").val(1)
                } else {
                    // console.log("我是isHot,我被选中了false 赋值为0")
                    $("#isHotId").val(0)
                }
            }
        });

        /*放这里的原因是  等到富文本和控件加载完成了 在初始化整个表单*/
        doInitFormData()


        // 批量上传图片用
        var input = document.getElementById("images");
        var result, div;

        if (typeof FileReader === 'undefined') {
            result.innerHTML = "抱歉，你的浏览器不支持 FileReader";
            input.setAttribute('disabled', 'disabled');
        } else {
            input.addEventListener('change', readFile, false);
        }

        function readFile() {
            // 取到所有文件然后发请求 把路径拼接给imagesValueId
            var data = new FormData();
            let files = $('#images')[0].files;
            for (let i = 0; i < files.length; i++) {
                data.append("files", files[i]);
            }
            $.ajax({
                url: '/file/uploads',
                type: 'POST',
                data: data,
                processData: false,//建议添加，否则值传可能不到对应url
                contentType: false,//建议添加，否则值可能传不到对应url
                success: function (arg) {
                    $("#imagesValueId").val(arg)
                    console.log(arg)
                },
                error: function (arg) {
                    console.log(arg);
                    alert("失败")
                }
            });


            for (var i = 0; i < this.files.length; i++) {
                if (!input['value'].match(/.jpg|.gif|.png|.bmp/i)) {　　//判断上传文件格式
                    return alert("上传的图片格式不正确，请重新选择")
                }
                var reader = new FileReader();
                reader.readAsDataURL(this.files[i]);
                reader.onload = function (e) {
                    result = '<span id="result"><img  style="height: 80px;width: 80px" src="' + this.result + '" alt=""/></span>';
                    span = document.createElement('span');
                    span.innerHTML = result;
                    document.getElementById('imagesDiv').appendChild(span);  　　//插入dom树                      <br>　　　　　　　　　　}
                }
            }
        }

    });

    // 封面图上传
    function changeImage() {
        var data = new FormData();
        var len = $('#ImagesId')[0].files.length;
        for (var i = 0; i < len; i++) {
            var file = $('#ImagesId')[0].files[i];
            data.append('file', file);//将图片信息file保存到该对象
        }
        ;

        if (len == 0) {
            alert("未上传图片！");
        } else {
            $.ajax({
                url: '/file/upload',
                type: 'POST',
                data: data,
                processData: false,//建议添加，否则值传可能不到对应url
                contentType: false,//建议添加，否则值可能传不到对应url
                success: function (arg) {
                    $("#gimage").show()
                    $("#gimage").attr("src", arg)
                    $("#picUrlId").val(arg);
                },
                error: function (arg) {
                    console.log(arg);
                    $('#result').html(arg);
                    alert("失败")
                }
            });
        }
    }

    function doInitFormData() {
        var data = $("#mainContentId").data("rowData");
        if (!data) return;

        //初始化spu信息
        $("#spuId").val(data.id);
        $("#nameId").val(data.name);
        $("#goodsSnId").val(data.goodsSn);

        $("#categoryId [selected='selected']").attr("selected", false);
        $("#categoryId [value='" + data.categoryId + "']").attr("selected", "selected")

        $("#shopId [selected='selected']").attr("selected", false);
        $("#shopId [value='" + data.shopId + "']").attr("selected", "selected")

        $("#brandId [selected='selected']").attr("selected", false);
        $("#brandId [value='" + data.brandId + "']").attr("selected", "selected")

        // 相册
        let images = JSON.parse(data.gallery);
        $("#imagesValueId").val(data.gallery);
        for (var i = 0; i < images.length; i++) {
            result = '<span id="result"><img  style="height: 80px;width: 80px" src="' + images[i] + '" alt=""/></span>';
            span = document.createElement('span');
            span.innerHTML = result;
            document.getElementById('imagesDiv').appendChild(span);
        }


        $("#keywordsId").val(data.keywords);
        $("#numId").val(data.num);
        $("#briefId").val(data.brief);
        $("#isOnSaleId").bootstrapSwitch('state', data.isOnSale === 1);
        $("#isOnSaleId").val(data.isOnSale === 1?1:0)
        $("#sortOrderId").val(data.sortOrder);
        $("#gimage").attr("src", data.picUrl);
        $("#picUrlId").val(data.picUrl)
        $("#isNewId").bootstrapSwitch("state", data.isNew === 1);
        $("#isNewId").val(data.isNew === 1?1:0)
        $("#isHotId").bootstrapSwitch("state", data.isHot === 1);
        $("#isHotId").val(data.isHot === 1?1:0)
        $("#unitId").val(data.unit);
        $("#counterPriceId").val(data.counterPrice);
        $("#retailPriceId").val(data.retailPrice);

        window.UE.getEditor('editor').addListener("ready", function () {
            // editor准备好之后才可以使用
            window.UE.getEditor('editor').setContent(data.detail);

        });

    }

    function doCancel() {
        $("#mainContentId").removeData("rowData");
        sessionStorage.setItem("isSpu",true)
        window.location.reload();
        $("#mainContentId").load("/spu");
    }


    function doSaveOrUpdate() {
        var rowData = $("#mainContentId").data("rowData");
        //1.获取表单数据 var strdata = $("#formID").serializeArray();
        var params = $("form").serialize();
         params = JSON.stringify(params);

        //2.发起异步请求
        var insertUrl = "spu/add";
        var updateUrl = "spu/edit";
        var url = rowData ? updateUrl : insertUrl;
        console.log(params);
        $.post(url, params, function (result) {
            if (result.state == 1) {
                if (rowData) {
                    alert("修改成功");
                } else {
                    alert("保存成功")
                }
                doCancel();
            } else {
                alert(result.message);
            }
        })
    }


</script>






